<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图区 -->

		<el-card>
			<!-- 警告区域 -->
			<el-alert title="注意只允许为第三方分类设置相关参数!" type="warning" show-icon :closable="false">
			</el-alert>
			<!-- 选择商品分类区域 -->
			<el-row>
				<el-col class="cat_opt">
					<span>选择商品分类：</span>
					<!-- 级联选择框 -->
					<!-- option用来指定数据源 -->
					<!-- props用来配置对象 -->
					<!-- v-model 必须绑定一个数组 选择多级时用数组存放每级id -->
					<!-- clearable 可以x input框 -->
					<!--  change-on-select可以选择任意一级 -->
					<el-cascader expand-trigger="hover" v-model="selectedCateKeys" :options="catelist"
						:props="CateProps" @change="CateChanged">
					</el-cascader>
				</el-col>
			</el-row>
			<!-- tab页签区域 -->
			<el-tabs v-model="activeName" @tab-click="handleTabClick">
				<!-- 添加动态参数的面板 -->
				<el-tab-pane label="动态参数" name="many">

					<el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="adddialogVisible=true">添加参数
					</el-button>
					<el-table :data="manyTableData" border stripe>
						<!-- 展开行 -->
						<el-table-column type="expand">
							<template slot-scope="scope">
								<!-- 循环渲染tag -->
								<el-tag @close="handleClose(i,scope.row)" closable
									v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
								<!-- 添加的tag输入框 -->
								<el-input class="input-new-tag" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<!-- 添加的button按钮 -->
								<el-button v-else type="primary" class="button-new-tag" size="small"
									@click="showInput(scope.row)">+ New Tag</el-button>
							</template>

						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="参数名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">

								<el-button @click="showEditDialog(scope.row.attr_id)" size="mini" type="primary"
									icon="el-icon-edit">编辑</el-button>
								<el-button size="mini" type="primary" icon="el-icon-delete"
									@click="removeparamsById(scope.row.attr_id)">删除</el-button>
							</template>

						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="静态属性" name="only">
					<el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="adddialogVisible=true">添加属性
					</el-button>
					<el-table :data="onlyTableData" border stripe>

						<!-- 展开行 -->
						<el-table-column type="expand">
							<template slot-scope="scope">
								<!-- 循环渲染tag -->
								<el-tag closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
								<!-- 添加的tag输入框 -->
								<el-input class="input-new-tag" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<!-- 添加的button按钮 -->
								<el-button v-else type="primary" class="button-new-tag" size="small"
									@click="showInput(scope.row)">+ New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="属性名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button @click="showEditDialog(scope.row.attr_id)" size="mini" type="primary"
									icon="el-icon-edit">编辑
								</el-button>
								<el-button size="mini" type="primary" icon="el-icon-delete"
									@click="removeparamsById(scope.row.attr_id)">删除</el-button>
							</template>

						</el-table-column>
					</el-table>
				</el-tab-pane>

			</el-tabs>
		</el-card>
		<!-- 添加参数对话框 -->
		<el-dialog @close="adddialogclosed" :title="'添加'+titleText" :visible.sync="adddialogVisible" width="50%">
			<el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="addForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="adddialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveParams()">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 修改参数对话框 -->
		<el-dialog @close="editdialogclosed" :title="'修改'+titleText" :visible.sync="editdialogVisible" width="50%">
			<el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="editForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="editdialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editParams()">确 定</el-button>
			</span>
		</el-dialog>


	</div>
</template>

<script>
	export default {
		data() {
			return {
				// 商品分类列表
				catelist: [],
				//级联选择框配置对象
				CateProps: {
					value: 'cat_id',
					label: 'cat_name',
					children: 'children'
				},
				// 级联选中对应的id数组
				selectedCateKeys: [],
				// 被激活的页签的名称 默认展示的页
				activeName: 'many',
				// 动态参数数据
				manyTableData: [],
				// 静态属性的数据
				onlyTableData: [],
				// 控制添加参数对话框显示和隐藏
				adddialogVisible: false,

				// 添加参数的表单数据对象
				addForm: {
					attr_name: ''
				},
				// 添加表单验证规则对象
				addFormrules: {
					attr_name: [{
							required: true,
							message: '请输入参数名称',
							trigger: 'blur'
						}

					]
				},
				editdialogVisible: false,
				editForm: {

				},
				editFormrules: {
					attr_name: [{
							required: true,
							message: '请输入参数名称',
							trigger: 'blur'
						}

					]
				},
				// 控制tag输入框和按钮的切换
				inputVisible: false,
				// 双向绑定tag文本框中输入的内容
				inputValue: ''


			}
		},
		created() {
			this.getCateList()
		},
		computed: {
			// 如果按钮需要被禁用返回true则反回false
			isBtnDisabled() {
				if (this.selectedCateKeys.length !== 3) {
					return true
				}
				return false
			},
			// 当前选中的三级分类的Id
			cateId() {
				if (this.selectedCateKeys.length == 3) {
					// 拿到三级分类id
					return this.selectedCateKeys[2]
				}
				return null
			},
			//动态计算对话框标题
			titleText() {
				if (this.activeName === 'many') {
					return "动态参数"
				} else {
					return "静态属性"
				}
			}
		},
		methods: {
			// 获取分类数据
			async getCateList() {
				const {
					data: res
				} = await this.$http.get('categories')
				if (res.meta.status != 200) {
					return this.$message.error("获取商品分类失败")
				}
				//把数据列表赋值给catelist
				this.catelist = res.data


			},
			// 级联选择框中选择项变化时触发
			CateChanged() {
				this.getParamsDate()

			},
			// tab页签点击事件处理函数
			handleTabClick() {
				this.getParamsDate()
			},
			// 获取参数的列表数据
			async getParamsDate() {

				if (this.selectedCateKeys.length != 3) {

					this.selectedCateKeys = []

					this.manyTableData = []

					this.onlyTableData = []

					return

				} else {

					const {

						data: res

					} = await this.$http.get(`categories/${this.cateId}/attributes`, {

						params: {

							sel: this.activeName

						}

					})

					console.log(res)

					console.log(this.cateId)

					if (res.meta.status != 200) {

						return this.$message.error("获取参数列表失败")

					} else {

						res.data.forEach(item => {

							item.attr_vals = item.attr_vals ?

								item.attr_vals.split(' ') : []

							item.inputVisible = false

							item.inputValue = ''

						})

						if (this.activeName == 'many') {

							this.manyTableData = res.data

						} else {

							this.onlyTableData = res.data

						}

					}

				}



			},
			// 重置对话框表单数据
			adddialogclosed() {
				this.$refs.addFormRef.resetFields()
			},
			saveParams() {
				this.$refs.addFormRef.validate(async valid => {

					if (!valid) return
					const {
						data: res
					} = await this.$http.post(`categories/${this.cateId}/attributes`, {
						attr_name: this.addForm.attr_name,
						attr_sel: this.activeName
					})

					if (res.meta.status != 201) {
						return this.$message.error("添加参数失败" + res.data.msg)
					}

					//提示成功
					this.$message.success("添加成功")
					//刷新列表
					this.getParamsDate()
					//关闭对话框
					this.adddialogVisible = false


				})
			},
			async showEditDialog(attr_id) {
				// 查询当前参数的信息
				const {
					data: res
				} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
					params: {
						attr_sel: this.activeName
					}
				})

				if (res.meta.status != 200) {
					return this.$message.error("请求数据失败" + res.data.msg)
				}
				this.editForm = res.data
				this.editdialogVisible = true
			},
			editdialogclosed() {
				this.$refs.editFormRef.resetFields()
			},
			editParams() {

				this.$refs.editFormRef.validate(async valid => {

					if (!valid) return
					const {
						data: res
					} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
						attr_sel: this.activeName,
						attr_name: this.editForm.attr_name
					})

					if (res.meta.status !== 200) {
						return this.$message.error("修改参数失败")
					}

					//提示成功
					this.$message.success("添加成功")
					//刷新列表
					this.getParamsDate()
					//关闭对话框
					this.editdialogVisible = false


				})
			},
			// 移除参数事件

			async removeparamsById(role) {

				const confirmResult = await this.$confirm('此操作将永久删除参数, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					//如果用户取消删除则 则打印cancel字符串
					.catch(err => err)
				//如果用户确认删除则confirmResult 为confim字符串

				if (confirmResult != 'confirm') {
					return this.$message.info("已经取消删除")
				}
				const {
					data: res
				} = await this.$http.delete(`categories/${this.cateId}/attributes/${role}`)
				if (res.meta.status != 200) {
					return this.$message.error("删除失败")
				}
				this.$message.success("删除成功")
				this.getParamsDate()

			},
			// 在tag输入框中回车或者失去焦点时触发
			async handleInputConfirm(hang) {
				console.log(hang)
				if (hang.inputValue.trim().length === 0) {
					hang.inputValue = ''
					hang.inputVisible = false
					return
				}

				// 如果没有return证明输入了内容然后处理
				hang.attr_vals.push(hang.inputValue.trim())
				hang.inputValue = ''
				hang.inputVisible = false


				const {
					data: res
				} = await this.$http.put(`categories/${this.cateId}/attributes/${hang.attr_id}`, {
					attr_name: hang.attr_name,
					attr_sel: hang.attr_sel,
					attr_vals: hang.attr_vals.join(' ')

				})
				if (res.meta.status !== 200) {
					return this.$message.error("修改失败")
				}
				return this.$message.success("修改成功")

			},
			// 当点击tag添加按钮时切换为输入框
			showInput(row) {
				row.inputVisible = true
				// 让文本框自动获得焦点
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				})
			},
			// 删除参数函数
			async saveAttrVals(hang) {
				const {
					data: res
				} = await this.$http.put(`categories/${this.cateId}/attributes/${hang.attr_id}`, {
					attr_name: hang.attr_name,
					attr_sel: hang.attr_sel,
					attr_vals: hang.attr_vals.join(' ')

				})
				if (res.meta.status !== 200) {
					return this.$message.error("修改失败")
				}
				return this.$message.success("修改成功")
			},
			// 删除参数事件
			handleClose(i, row) {
				row.attr_vals.splice(i, 1)
				this.saveAttrVals(row)

			}

		}
	}
</script>

<style lang="less" scoped="scoped">
	.cat_opt {
		margin: 15px 0;
	}

	.el-tag {
		margin: 10px;
	}

	.input-new-tag {
		width: 120px;
	}
</style>
